/*
 * @Author: fanjs
 * @Date: 2025-03-19 10:36:03
 * @Description:
 */
import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { useDisclosure, addToast, Button, Input, Modal, ModalContent, ModalHeader, ModalBody, ModalFooter, Spinner } from '@heroui/react';
import type { EmailItem } from './types';
import ConfigList from './components/ConfigList';
import ConfigDrawer from './components/OperaDrawer';
import { SvgIcon } from "@/components/SvgIcon";
import { fetchEmailListApi, verifyStatusApi, deleteConfigApi } from '@/service/api';
import { useNavigate } from 'react-router-dom';
import { localStg } from '@/utils/storage';

const EmailConfig: React.FC = () => {
  const navigate = useNavigate();
  const { isOpen: isDeleteOpen, onOpen: onOpenDelete, onOpenChange: onOpenDeleteChange } = useDisclosure();
  const { isOpen: isOperaOpen, onOpen: onOpenOpera, onOpenChange: onOpenOperaChange } = useDisclosure();

  const [loading, setLoading] = useState(true);

  const [operaRow, setOperaRow] = useState<EmailItem>({} as EmailItem);

  const [list, setList] = useState<EmailItem[]>([]);
  const [connectedId, setConnectedId] = useState(''); // 当前已连接的邮箱ID

  // 搜索关键字
  const [searchKeyword, setSearchKeyword] = useState('');

  // 新增
  const onAddRow = useCallback(() => {
    setOperaRow({} as EmailItem);
    onOpenOpera();
  }, [onOpenOpera]);

  // 表格事件
  const tableEmit = {
    onDelete: (row: EmailItem) => {
      setOperaRow(row);
      onOpenDelete();
    },
    onConnect: (row: EmailItem) => {
      setOperaRow(row);
      onOpenOpera(); // 打开弹窗
    },
  }

  // 弹窗事件
  const operaEmit = {
    onClose: () => {
      setOperaRow({} as EmailItem);
      onOpenOperaChange();
    },
    onConnect: (row: EmailItem) => {
      setConnectedId(row.id)
      localStg.set('email_id', row.id)
      localStg.set('email_sender', row.email_account)
      fetchList()
    },
  }

  // 跳转至邮件内容
  const toContent = (row: EmailItem) => {
    localStg.set('email_id', row.id)
    localStg.set('email_sender', row.email_account)
    navigate(`/distribute/content`)
  }

  // 删除
  const confirmDelete = async () => {
    const { data } = await deleteConfigApi(operaRow.id as string);
    if (data) {
      addToast({ title: '删除成功' })
      if (operaRow.id === connectedId) {
        setConnectedId('')
        localStg.remove('email_id')
        localStg.remove('email_sender')
      }
      fetchList()
      onOpenDeleteChange();
    } else {
      addToast({ title: '删除失败' })
    }
  };

  // 获取列表
  const fetchList = async () => {
    setLoading(true);
    try {
      const { data } = await fetchEmailListApi();
      if (data) setList(data);
    } catch {
      addToast({ title: '获取列表失败' })
    } finally {
      setTimeout(() => setLoading(false), 300);
    }
  };

  // 检查邮箱连接状态
  const checkLinkStatus = async () => {
    const { data }: any = await verifyStatusApi();
    if (!data || !data.connecting) {
      setConnectedId('')
      localStg.remove('email_id')
      localStg.remove('email_sender')
      return
    }
    setConnectedId(data.id)
    localStg.set('email_id', data.id)
  }

  // 获取列表数据
  useEffect(() => {
    checkLinkStatus();
    fetchList();
  }, []);


  // 顶部筛选
  const topContent = useMemo(() => {
    return (
      <div className="flex flex-col">
        <div className="flex justify-between items-end gap-3">
          <div className="flex gap-2 w-[50%] sm:max-w-[600px] sm:w-[34%] relative">
            <Input
              className="w-full"
              placeholder="输入关键字查询"
              value={searchKeyword}
              onValueChange={setSearchKeyword}
            />
            <Button
              color="secondary"
              className="absolute right-1 top-1/2 -translate-y-1/2"
              size="sm"
              isIconOnly
              variant="flat"
              startContent={<SvgIcon icon="ri:search-line" />}
            >
            </Button>
          </div>
          <div className="flex gap-3">
            <Button onPress={onAddRow} color="secondary" startContent={<SvgIcon icon="ic:sharp-plus" className="text-lg -mx-1" />}>
              新增
            </Button>
          </div>
        </div>
      </div>
    );
  }, [searchKeyword, onAddRow]);

  return (
    <div className='p-4 relative'>
      {loading && (
        <div className="absolute top-0 left-0 w-full h-[calc(100vh-56px)] z-50 bg-default-100/50 flex justify-center items-center ">
          <Spinner size="lg" color="secondary" />
        </div>
      )}
      <ConfigList connectedId={connectedId} onConnect={tableEmit.onConnect} toContent={toContent} onDelete={tableEmit.onDelete} topContent={topContent} list={list} />

      {/* 新增编辑 */}
      <ConfigDrawer connectedId={connectedId} onConnect={operaEmit.onConnect} toContent={toContent} isOpen={isOperaOpen} onClose={operaEmit.onClose} rowData={operaRow} />

      {/* 删除拦截弹窗 */}
      <Modal
        isDismissable={false}
        isKeyboardDismissDisabled={true}
        isOpen={isDeleteOpen}
        onOpenChange={onOpenDeleteChange}
      >
        <ModalContent>
          {(onClose: () => void) => (
            <>
              <ModalHeader className="flex flex-col gap-1">确定删除？</ModalHeader>
              <ModalBody>将清空当前邮箱客户端配置，确定继续吗？</ModalBody>
              <ModalFooter className='gap-x-4'>
                <Button color="default" variant="flat" onPress={onClose}>取消</Button>
                <Button color="secondary" onPress={confirmDelete}>确定</Button>
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
    </div>
  );
};

export default EmailConfig;
